package com.woniu.filter;


import com.alibaba.fastjson.JSON;
import com.woniu.outlet.client.WorkingProcedures;
import com.woniu.util.JwtTokenUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@Component
public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private WorkingProcedures workingProcedures;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获得客户端请求的头信息
        String path = request.getRequestURI().toString();

        if (path.contains("doc.html") || path.contains(".js") || path.contains(".css")
                || path.contains("swagger-resources") || path.contains("api-docs")
                || path.contains("v2") || path.contains("favicon.ico") || path.contains("login")) {
            filterChain.doFilter(request, response);
            return;
        }
        //获取用户名
        String account = JwtTokenUitl.getUserName(request.getHeader("tokenStr"));
        //通过用户名查询该用户的权限集合
        String password = workingProcedures.getWorkerByAccount(account).getData();
        String s = redisTemplate.opsForValue().get(account + password);
        List<String> strings = JSON.parseArray(s, String.class);
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        for (String string : strings) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(string);
            grantedAuthorityList.add(simpleGrantedAuthority);
        }
        //将消息封装到认证对象中
        Authentication authen =
                new UsernamePasswordAuthenticationToken(account, "",grantedAuthorityList );
        //存入security上下文中
        SecurityContextHolder.getContext().setAuthentication(authen);
        //放行
        filterChain.doFilter(request, response);
    }
}
